//
//  Observable+ObjectMapper.swift
//  SwiftDemo
//
//  Created by 硕星 on 2019/4/22.
//  Copyright © 2019 ty. All rights reserved.
//

import Foundation
import RxSwift
import Moya
import ObjectMapper

extension Observable {
    func mapObject<T: Mappable>(type: T.Type) -> Observable<T> {
        return self.map{response in
//            print("extension map:\(response) ")
            guard let dict = response as? [String: Any] else {
                throw RXSwiftMoyaError.ParseJSONError
            }
            return Mapper<T>().map(JSON: dict)!
        }
    }
    func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
        return self.map { response in
            guard let array = response as? [Any] else{
                throw RXSwiftMoyaError.ParseJSONError
            }
            guard let dicts = array as? [[String: Any]] else {
                throw RXSwiftMoyaError.ParseJSONError
            }
            return Mapper<T>().mapArray(JSONArray: dicts)
        }
    }
    
}

enum RXSwiftMoyaError: String {
    case ParseJSONError
    case OtherError
}
extension RXSwiftMoyaError: Swift.Error {}
